﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace yule.Model
{
    /// <summary>
    /// 树辅助类
    /// </summary>
    public static class TreeHelper
    {
        /// <summary>
        /// 树形分隔符,PathId,PathName
        /// </summary>
        public const char TreeSeparator = '/';
        /// <summary>
        /// 获取树形层次名（已经去除第一个《树形分隔符 TreeHelper.TreeSeparator》）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tree"></param>
        /// <returns></returns>
        public static string GetPathName<T>(ITree<T> tree) where T : ITree<T>
        {
            string name = string.Empty;

            do
            {
                name = TreeHelper.TreeSeparator + tree.Name + name;

                tree = tree.Parent;

            } while (tree != null);

            return name;
        }

        /// <summary>
        /// 获取树形层次Id
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tree"></param>
        /// <returns></returns>
        public static string GetPathId<T>(ITree<T> tree) where T : ITree<T>
        {
            string id = string.Empty;

            do
            {

                id = TreeHelper.TreeSeparator + tree.Id + id;

                tree = tree.Parent;

            } while (tree != null);

            return id;
        }


        public static int GetLevel<T>(ITree<T> tree) where T : ITree<T>
        {
            return (tree.ParentId.Split(TreeHelper.TreeSeparator).Length - 1);
        }

    }
}